/*
 * 测肤报告主视图
 * @Author: ljb
 * @Date: 2018-05-11 14:02:45
 * @Last Modified by: ljb
 * @Last Modified time: 2019-05-17 16:35:12
 */
<style lang="less" rel="stylesheet/less" type="text/less">

    @import '~src/assets/css/common.less';

    .v-user-report-views {
		position: relative;
		box-sizing: border-box;
		// background-image: linear-gradient(90deg, #d0abfa 0%, #e099ec 100%);
			background-color: #FFBED6;
        /*顶部tab栏样式*/
        .nav-tabs {
            display: flex;
            width: 100%;
            justify-content: space-around;
			height: 88* @rem-per-px;
			font-size:30px;
			font-weight:400;
			line-height:88* @rem-per-px;
			color:rgba(255,255,255,1);
			border-bottom: 2px solid rgba(255,255,255,0.3);

            & > div {
                position: relative;
                width: 30%;
                height: 100%;
                line-height: @tab-height;
                text-align: center;
                font-size: @main-font;
                box-sizing: border-box;
				transition: color .3s 0s ease;
				opacity:0.5;
                &::after{
                    content: '';
                    position:absolute;
                    top: 100%;
					left: 0;
					// left:36px;
					// right:38px;
                    right: 0;
                    height: 2px;
                    background-color: #ffffff;
                    transition: transform .3s;
                    transform: scale(0);
                }
                &.checked {
					opacity:1;
					color: #ffffff;
                    &::after {
                        transform: scale(1);
                    }
                }
                &.touch {
                    &::after{
                        transform-origin: 100%;
                    }
                }
                &.image {
                    &::after{
                        transform-origin: 0%;
                    }
				}
				&.no-cn {
					font-size: @sub-font;
					white-space: nowrap;
					// overflow: hidden;
					text-overflow: ellipsis;
				}
            }
        }
        /*顶部tab栏样式 END*/
        /*没有测肤记录*/
        .no-skin-test {
            width: 100%;
            height: 100%;
            padding-top: 166*@rem-per-px;
            text-align: center;
            box-sizing: border-box;
            .no-test-image {
                width: 316*@rem-per-px;
                height: 240*@rem-per-px;
            }
            .tip {
                margin-top: 70*@rem-per-px;
                margin-bottom: 16*@rem-per-px;
                font-size: @main-font;
                font-weight: bold;
                text-align: center;
                color: @main-font-color;
            }
            .text {
                text-align: center;
                font-size: @sub-info-font;
                color: @info-color;
            }
        }
        /*没有测肤记录 END*/
    }

</style>
<template>
	<div class="v-user-report-views">
		<back v-if="!$status.isWxBrowser()"/>
		<div class="nav-tabs">
			<div
				v-for="(tab,index) in nav_tabs"
				:key="index"
				:class="[tab.class,{'checked': selected_tab === tab.value,'no-cn': $t('lang') !== 'CN'}]"
				@click="changeTab(tab.value)">
				{{ tab.name }}
			</div>
		</div>

		<component
			:is="component_map[selected_tab]"
			:records="skinRecords"
			:sex="request_param.sex"
			:product="recommend_product"
			:generate="generateSolution"/>
	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';
import { mapGetters, mapMutations, mapActions } from 'vuex';
import Vue from 'vue';
import qs from 'qs';
import Back from 'src/views/component/back';
import touchReport from './touch-skin-report.vue'; // 智能测肤组件
import imageReport from './image-skin-report.vue'; // 3D测肤组件

export default {
	name: 'ReportViews',
	components: {
		touchReport,
		imageReport,
		back: Back,
	},
	data() {
		return {
			request_param: {
				openid: null,
				appid: null,
				skin_record_id: null,
				skin_detector_id: null,
				type_skin_record_id: null,
				sex: null,
			}, // openid和appid，用于请求报告列表

			selected_tab: '',

			nav_tabs: [
				{
					class: 'touch',
					name: this.$t('report.touch_test'), // 智能测肤
					value: 3,
				},
				{
					class: 'image',
					name: this.$t('report.image_test'), // 3D测肤
					value: 2,
				},
			],

			component_map: {

				2: 'imageReport',

				3: 'touchReport',

			}, // 组件映射表

			icon: require('src/assets/media/img/user/records/logo.png'),

			skin_record: {}, // 测肤数据

			recommend_product: [], // 商品推荐

		};
	},
	computed: {

		...mapGetters('userInfo', [
			'getUserInfo',
			'getAppid',
		]),

		...mapGetters('lang', [
			'getLang',
		]),

		/**
         * 返回测肤数据数组
         * @return {Array} {测肤数据数组}
         */
		skinRecords() {
			const key = this.component_map[this.request_param.skin_detector_id]; // 组件名
			return this.skin_record[key] || [];
		},

	},
	mounted() {
		this.initData();
	},
	methods: {

		...mapMutations('report', [
			'saveOptions',
			'saveActiveOption',
			'saveGeneratedProductGroups',
		]),

		...mapActions('report', [
			'fetchRecommendProductGroup',
		]),

		/**
         * 初始化页面数据
         * @return {promise} 获取肤质检测报告
         */
		initData() {
			this.request_param.openid = this.getUserInfo.openid;
			this.request_param.appid = this.getUserInfo.appid || this.$status.appid;
			this.request_param.skin_detector_id = this.getSkinDetectorId(); // 智能测肤的 value 值
			return this.changeTab(this.request_param.skin_detector_id);
		},

		/**
		 * 获取tab的值
		 */
		getSkinDetectorId() {
			return this.$route.query.skin_detector_id || parseInt(this.$status.skin_detector_id, 10) || 3;
		},

		/**
         * 改变tab
         * @param  {string} value {tab的value值}
         * @return {undefined}
         */
		changeTab(value) {
			if (this.selected_tab === value) return;

			this.request_param.skin_detector_id = value; // 测肤类型

			this.fetchSkinTestReport(this.request_param, value);
		},

		/**
         * 获取测肤报告
         * @param  {Object} param {description}
         * @return {type} {description}
         */
		fetchSkinTestReport(params, value) {
			const key = this.component_map[value];

			if (this.skin_record[key]) { // 缓存
				this.selected_tab = value;
				return;
			}

			this.$http.get(API_LIST.NEW_SKIN_RECORD, { params })
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.saveDataAccordingToType(data.skin_records, value);

					this.selected_tab = value;

					this.request_param.sex = data.wechat_user_info ? data.wechat_user_info.sex : 'null';
				})
				.catch((err) => {
					const toast = this.$createToast({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText,
					});
					toast.show();
				});
		},

		/**
         * 获取商品推荐的数据
         * @param  {Object} param {description}
         * @return {type} {description}
         */
		fetchRecommendProduct(param) {
			const query_str = qs.stringify(param);
			this.$http.get(`${API_LIST.RECOMMEND_PRODUCT}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					this.recommend_product = data.recommend_products;
				})
				.catch((err) => {
					const toast = this.$createToast({
						type: 'error',
						time: 2000,
						txt: err.message || err.statusText,
					});
					toast.show();
				});
		},

		/**
         * 根据类型存储数据
         * @return {undefined}
         */
		saveDataAccordingToType(data, value) {
			const key = this.component_map[value];

			Vue.set(this.skin_record, key, data);
		},

		generateSolution({ type, options, active_option }) {
			const { skin_record_id, id } = active_option;
			this.request_param.skin_record_id = skin_record_id;
			this.request_param.type_skin_record_id = id;
			return this.fetchRecommendProductGroup(this.request_param)
				.then((result) => {
					this.saveOptions({ type, options });
					this.saveActiveOption({ type, active_option });
					this.saveGeneratedProductGroups({ type, product_groups: result });
					return true;
				}).catch((error) => {
					const toast = this.$createToast({
						type: 'error',
						time: 2000,
						txt: error.message || error.statusText,
					});
					toast.show();
				});
		},

	},
};
</script>
